import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:camera/camera.dart';
import '../services/recording_service.dart';

class CameraScreen extends StatefulWidget {
  final List<CameraDescription> cameras;

  const CameraScreen({super.key, required this.cameras});

  @override
  State<CameraScreen> createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraScreen> {
  bool isCameraInitialized = false;

  @override
  void initState() {
    super.initState();
    _initializeViaService();
  }

  Future<void> _initializeViaService() async {
    try {
      await RecordingService.instance.ensureInitialized(widget.cameras);
      setState(() {
        isCameraInitialized = true;
      });
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('相机初始化失败: $e')),
      );
    }
  }

  Future<void> _startRecording() async {
    try {
      await RecordingService.instance.startRecording();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('开始录制...')),
      );
      setState(() {});
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('开始录制失败: $e')),
      );
    }
  }

  Future<void> _stopRecording() async {
    try {
      final savedPath = await RecordingService.instance.stopRecording();
      if (savedPath != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('视频已保存到: $savedPath')),
        );
      }
      setState(() {});
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('停止录制失败: $e')),
      );
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!isCameraInitialized || !RecordingService.instance.isInitialized) {
      return const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('监控录制'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: Column(
        children: [
          Container(
            height: 240,
            width: double.infinity,
            color: Colors.black,
            child: CameraPreview(RecordingService.instance.controller!),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton.icon(
                  onPressed: () => RecordingService.instance
                      .setOrientation(DeviceOrientation.portraitUp),
                  icon: const Icon(Icons.stay_current_portrait),
                  label: const Text('竖屏'),
                ),
                const SizedBox(width: 8),
                ElevatedButton.icon(
                  onPressed: () => RecordingService.instance
                      .setOrientation(DeviceOrientation.landscapeLeft),
                  icon: const Icon(Icons.stay_current_landscape),
                  label: const Text('横屏L'),
                ),
                const SizedBox(width: 8),
                ElevatedButton.icon(
                  onPressed: () => RecordingService.instance
                      .setOrientation(DeviceOrientation.landscapeRight),
                  icon: const Icon(Icons.stay_current_landscape),
                  label: const Text('横屏R'),
                ),
              ],
            ),
          ),
          Expanded(
            child: Center(
              child: ValueListenableBuilder<bool>(
                valueListenable: RecordingService.instance.recording,
                builder: (context, recording, _) {
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      FloatingActionButton(
                        onPressed: recording ? _stopRecording : _startRecording,
                        backgroundColor: recording ? Colors.red : Colors.blue,
                        child: Icon(
                          recording ? Icons.stop : Icons.videocam,
                          size: 30,
                          color: Colors.white,
                        ),
                      ),
                      if (recording) ...[
                        const SizedBox(width: 20),
                        const Text(
                          '录制中...',
                          style: TextStyle(color: Colors.red, fontSize: 16),
                        ),
                      ],
                    ],
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}
